package com.cande.gcclean;

import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;

public class GCCleanTest {
    static class Resource {
        // 模拟资源
    }

    static class CleanupTask extends PhantomReference<Resource> {
        public CleanupTask(Resource referent, ReferenceQueue<? super Resource> q) {
            super(referent, q);
        }

        public void cleanup() {
            System.out.println("Resource is being cleaned up");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ReferenceQueue<Resource> queue = new ReferenceQueue<>();
        Resource resource = new Resource();
        CleanupTask cleanupTask = new CleanupTask(resource, queue);

        // 释放对资源的强引用
        resource = null;

        // 触发垃圾回收
        System.gc();
        System.runFinalization();

        // 检查引用队列
        CleanupTask reference;
        while ((reference = (CleanupTask) queue.poll()) != null) {
            reference.cleanup();
        }
    }
}
